package com.itheima.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.itheima.canal.config.RabbitMQConfig.GOODS_UP_EXCHANGE;

/**-----------------------------------
  *         MYCODE ANNOTATION         *
  *------------------------------------
  * @date: 2020-7-22 15:11            *
  * @auther: WenJ                     *
  * @Description:                     *
  * 
  *----------------------------------*/
 
@CanalEventListener
public class SpuListener1 {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * spu 表更新
     * @param eventType
     * @param rowData
     */
    @ListenPoint(schema = "changgou_goods", table = {"tb_spu"},eventType = CanalEntry.EventType.UPDATE )
    public void spuUp(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {

        System.err.println("我的tb_spu表数据发生变化");

        // 获取修改前的数据，封装到oldMap中
        List<CanalEntry.Column> beforeColumnsList = rowData.getBeforeColumnsList();
        Map<String,String> oldMap = new HashMap<>();
        beforeColumnsList.forEach((c)->oldMap.put(c.getName(),c.getValue()));

        // 获取修改后的数据，封装到newMap中
        List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
        Map<String,String> newMap = new HashMap<>();
        afterColumnsList.forEach((c)->newMap.put(c.getName(),c.getValue()));


        // 判断如果oldmap中的上架由0变为1，则通知es
        if ("0".equals(oldMap.get("is_marketable")) && "1".equals(newMap.get("is_marketable"))){
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",newMap.get("id"));
            System.out.println("上架");
        }


        // 下架
        if ("1".equals(oldMap.get("is_marketable")) && "0".equals(newMap.get("is_marketable"))){
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE,"",newMap.get("id"));

            System.out.println("下架");
        }



        // 判断如果oldmap中的上架由0变为1，则发送消息到page服务
        if ("0".equals(oldMap.get("status")) && "1".equals(newMap.get("status"))){

            // 将商品的id发送给rabbitMQ
            rabbitTemplate.convertAndSend(GOODS_UP_EXCHANGE,"",newMap.get("id"));
            System.out.println("页面静态化id"+newMap.get("id"));
        }



    }
}
